package cn.dy.sbo.userImpl;

import cn.dy.sbo.core.UserManager;
import cn.dy.sbo.model.User;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Locale;
import java.util.Set;

public class UserDetailsServiceImpl implements UserDetailsService
{

    @Autowired
    private UserManager userManager;

    @Autowired
    private MessageSource messages;
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException
    {

        User user = userManager.getByUserName(username);
        if (user == null)
        {
            throw new UsernameNotFoundException(messages.getMessage("msg.userunfound",new Object[]{username}, Locale.ENGLISH));
        }

        if (!user.isValid())
        {
            throw new UsernameNotFoundException(messages.getMessage("msg.userunvalid",new Object[]{username}, Locale.ENGLISH));
        }

        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

        UserImpl userdetails = new UserImpl(user.getUsername(), user
                .getPassword(), enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, grantedAuths);

        userdetails.setId(user.getId());
        userdetails.setName(user.getName());
        return userdetails;
    }

    /**
     * 获得用户所有角色的权限集合.
     */
    private Set<GrantedAuthority> obtainGrantedAuthorities(User user)
    {
        Set<GrantedAuthority> authSet = Sets.newHashSet();

        String role = user.getRole();
        if(role != null)  {
            String[] roles=role.split(",") ;
            for(String r:roles)
                authSet.add(new GrantedAuthorityImpl(r));
        }
        return authSet;
    }

}
